import React, { Component } from 'react';
import {
	StyleSheet, Text, View, TouchableOpacity,
	Image, PixelRatio, FlatList
} from "react-native";
import { API, API_GENERATE } from '../../../../config/api';
import { GLOBAL } from '../../../../config/global';
import StorageHelper from '../../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../../config/storage';
import { style } from '../../../../theme/style';
import { Common } from '../../../../component/common/Common';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';
import HTTP from '../../../../utils/http';
import Dictionary from '../../../../utils/dictionary';
import MethodUtil from '../../../../utils/MethodUtil';
import ToastUtil from '../../../../utils/toast';
const scale = GLOBAL.SCALE;
import { SearchInput } from '../../../../component/SearchInput.js';
import { InputModel } from './_component/InputModel';
import { DelayModel } from './_component/DelayModel';
import { ListItem } from './_component/ListItem';
import { RangTime } from '../../../../component/common/RangTime.js';
import { NavigationEvents } from 'react-navigation';
import { NewAccount } from '../../../../components/common/newAccount';
import { SlideSelect } from '../../../../components/common/slideSelect';

let sendData = {
	onrefresh: false,
	pageNo: 1,
	pageSize: 20,
};

export class JudgementListPage extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			headerTitle: '授信逾期评判列表',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../../../imgs/goBackEmpty.png')} />),
			headerStyle: style.head.headerStyle,
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center',
			}
		}
	};

	constructor(props) {
		super(props);
		const { choice } = props.navigation.state.params || {};
		this.state = {
			selectVal: null,
			modeIndex: 0,
			modalVisible: false,
			tabIndex: 0,
			inputModelShow: false,
			loadIcon: false,  // 下拉涮新的 图标
			timeModel: false,//时间显示,
			timeStart: null,
			timeEnd: null,
			overdueInfo: {},
			newLotData: [],
			loading: true,
			alertShow: false,
			options: [],
			choice: choice || {}
		}
		this.pageNo = 1;
		this.totalPage = 1;
		this._closeModel = this._closeModel.bind(this);
		this._submit = this._submit.bind(this);
		this.inputModelData = {
			visible: false,
			submitText: '确认逾期',
			titleText: '逾期原因',
			tipText: '',
			btnPress: () => { },
			closePress: () => { }
		};
		this.delayModelData = {
			visible: false,
			btnPress: () => { },
			closePress: () => { }
		};
	}

	_closeModel () {
		const { inputModelShow } = this.state;
		this.inputModelData.visible = false;
		this.delayModelData.visible = false;
		this.setState({
			inputModelShow: !inputModelShow,
		})
	}

	_showModel (data) {
		const { overdueStatus } = data;
		const { inputModelShow } = this.state;
		this.setState({
			actionData: data
		})
		/**
		 * 0:延期
		 * 1:逾期
		 * 2:关闭
		 */
		if (overdueStatus === '0') {
			this.delayModelData.visible = true;
			this.delayModelData.data = data;
			this.delayModelData.closePress = () => { this._closeModel() };
			this.delayModelData.btnPress = (day,reason) => {
				this.delayModelData.visible = false;
				this.setState({
					inputModelShow: !inputModelShow,
				})
				this._submit(day,reason);
			}
		} else {
			this.inputModelData.visible = true;
			this.inputModelData.titleText = overdueStatus === '1' ? '逾期原因' : '关闭原因';
			this.inputModelData.tipText = overdueStatus === '1' ? '' : '（关闭后无法修改，请谨慎操作）';
			this.inputModelData.submitText = overdueStatus === '1' ? '确认逾期' : '确认关闭';
			this.inputModelData.closePress = () => { this._closeModel() };
			this.inputModelData.btnPress = (remark) => {
				this._submit(remark);
			}
		}
	}

	async _submit (value,reason) {
		const { actionData, inputModelShow } = this.state;
		const { overdueStatus, overdueId, checkDay, companyId } = actionData || {};
		this.inputModelData.visible = false;
		this.delayModelData.visible = false;
		if (overdueStatus === '0' && !value) {
			ToastUtil.showWarning('延期请输入延期天数');
		}
		this.setState({ inputModelShow: !inputModelShow });
		let responseData = await HTTP.POST(API_GENERATE(API.CREDIT_OVERDUE_DECIDE), {
			remark: overdueStatus === '0' ? 'APP操作延期' : value,
			overdueId,
			overdueStatus,
			companyId,
			reason: overdueStatus === '0' ? reason :'7',
			checkDay: overdueStatus === '0' ? value : '',
		});
		if (responseData) {
			this._getListData();
		}
	}

	async componentWillMount () {
		let creditFitlerTypes = await Dictionary.get('FIN_OVERDUE_DEAL');
		this.setState({ creditFitlerTypes });
		await this.getSorage();
		await this._getListData();
	}

	//获取业务组织
	async	getSorage () {
		const userInfoJson = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
		const userInfo = JSON.parse(userInfoJson);
		this.setState({
			options: userInfo.corpInfoTOs || [],
			choice: this.state.choice.corpId ? this.state.choice : userInfo.corpInfoTOs[0]
		})
	}

	// select 点击
	_itemFn = (sendObj, index) => {
		this.pageNo = 1;
		this._showVisible();
		this.setState({
			modeIndex: sendObj ? index : '',
			selectVal: sendObj ? sendObj.dictName : '全部',
			selectKey: sendObj ? sendObj.dictKey : ''
		}, function () {
			this._getListData({
				pageNo: 1,
				onrefresh: false
			});
		});
	}

	//点击显示隐藏
	_showVisible = () => {
		this.setState({
			modalVisible: !this.state.modalVisible
		})
	}

	//获取待审批,已审批列表
	async _getListData (agentObj) {
		const { timeStart, timeEnd, selectKey, searchTxt, choice } = this.state
		Object.assign(sendData, agentObj);
		sendData.startDate = timeStart;
		sendData.endDate = timeEnd;
		sendData.searchCode = searchTxt || '';
		sendData.overdueStatus = selectKey || '';
		sendData.corpId = choice.corpId;
		let responseData = await HTTP.POST(API_GENERATE(API.CREDIT_OVERDUE_LIST), sendData);
		this.setState({ loadIcon: false, loading: false });
		if (responseData) {
			this.setState({
				overdueInfo: responseData
			})
			if (responseData.paginationModel) {
				this.totalPage = responseData.paginationModel.totalPage;
				if (sendData.onrefresh) {  // 加载
					this.setState({
						newLotData: this.state.newLotData.concat(responseData.paginationModel.rows),
						status: 'data'
					})
				} else { // 刷新
					this.setState({
						newLotData: responseData.paginationModel.rows,
						status: responseData.paginationModel.rows.length ? 'data' : 'empty'
					})
				}
			} else {
				this.setState({
					status: 'error'
				})
			}
		} else {
			this.setState({
				status: 'error'
			})
		}
	}

	// 下拉更新函数
	_isLoadRefresh () {
		this.pageNo = 1;
		this.setState({ loadIcon: true })
		this._getListData({
			pageNo: 1,
			onrefresh: false
		});
	}

	//上拉加载
	_loadData () {
		if (this.totalPage > this.pageNo) {
			this.pageNo++;
			this._getListData({
				pageNo: this.pageNo,
				onrefresh: true
			});
		}
	}

	_renderItem (data) {
		return (
			<ListItem data={data.item} btnPress={(data) => this._showModel(data)} navigation={this.props.navigation} choice={this.state.choice} />
		)
	}

	_cancelCall = () => {
		this.setState({
			timeModel: false
		})
	}

	_resultCall = (resultData) => {
		this.pageNo = 1;
		this.setState({ loading: true });
		this.setState({
			timeStart: resultData.startTime,
			timeEnd: resultData.endTime,
			timeModel: false
		}, () => {
			this._getListData({
				pageNo: this.pageNo,
				onrefresh: false
			});
		})
	}

	_onErrorPress () {
		this.pageNo = 1;
		this._getListData({
			pageNo: 1,
			onrefresh: false
		});
	}

	_searchAddress (txt) {
		this.pageNo = 1;
		this.setState({ loading: true });
		this.setState({
			searchTxt: txt
		}, function () {
			this._getListData({
				pageNo: this.pageNo,
				onrefresh: false
			});
		})
	}

	render () {
		const searchLeft = require('../../../../imgs/customer/searchLeft.png');
		let { modalVisible, timeModel, selectVal, timeStart, timeEnd, status, overdueInfo, creditFitlerTypes,
			alertShow, choice, options } = this.state;
		let { totalOverdueAmount, totalOrderCnt } = overdueInfo || {};
		return (
			<View style={styles.container}>
				<NavigationEvents onWillFocus={async () => {
					await this.getSorage();
					await this._isLoadRefresh()
				}} />
				{options.length > 1 ? <NewAccount fn={(val) => { this.setState({ alertShow: val }) }} choice={choice.corpName || ''} /> : null}
				<View style={styles.headBox}>
					{/* <View style={styles.headTab}>
						<Text style={styles.tabText}>赊销</Text>
					</View> */}
					<View style={styles.outSearch}>
						<Text style={styles.tabText}>赊销</Text>
						<View style={styles.nerSearch}>
							<SearchInput
								placeholder={'请输入企业名称/订单号'}
								inputLeftIcon={searchLeft}
								setKeyWord={(txt) => { this._searchAddress(txt) }}
								onChangeText={(txt) => { }}
								onSubmitEditing={(txt) => { }}
								inputViewStyle={styles.searchStyle}
								inputLeftIconStyle={styles.searchLeftIconStyle}
								placeholderTextColor={'#fff'}
							/>
						</View>
					</View>
					<View style={styles.showBoxOut}>
						<View style={styles.showBox}>
							<View style={styles.showBoxItem}>
								<Text style={styles.showTitle}>逾期总额（元）</Text>
								<Text style={styles.showText}>￥{MethodUtil.toThousands(totalOverdueAmount, 2) || '-'}</Text>
							</View>
							<View style={styles.showBoxItem}>
								<Text style={styles.showTitle}>订单总数（笔）</Text>
								<Text style={styles.showText}>{totalOrderCnt || '-'}</Text>
							</View>
						</View>
					</View>

				</View>
				<View style={styles.listBoxOut}>
					<View style={styles.listScreen}>
						<TouchableOpacity onPress={this._showVisible} style={styles.flexRow}>
							<Text style={styles.allBtn}>{selectVal || '全部'}</Text>
							<Image source={require('../../../../imgs/select.png')} />
						</TouchableOpacity>
						<TouchableOpacity onPress={() => { this.setState({ timeModel: !timeModel }) }} style={styles.dateSelect}>
							<View style={styles.timeRight}>
								<Text style={styles.timeTitle}>到期日</Text>
								<Text style={styles.timeValue}>{timeStart || '开始时间'} / {timeEnd || '结束时间'}</Text>
							</View>
							<Image source={require('../../../../imgs/time.png')} style={{ width: 14 * scale, height: 16 * scale }}></Image>
						</TouchableOpacity>
					</View>
					{
						modalVisible && creditFitlerTypes ?
							<View style={styles.selects}>
								<TouchableOpacity onPress={() => this._itemFn()} style={styles.selectItem}>
									<Text style={styles.selectText}>全部</Text>
								</TouchableOpacity>
								{
									creditFitlerTypes.map((item, index) => {
										return (
											<TouchableOpacity key={index} onPress={() => this._itemFn(item, index)} style={styles.selectItem}>
												<Text style={styles.selectText}>{item.dictName}</Text>
											</TouchableOpacity>
										)
									})
								}
							</View>
							: null
					}
					{
						status === 'data' ?
							<FlatList
								data={this.state.newLotData}
								renderItem={(data) => this._renderItem(data)}
								refreshing={this.state.loadIcon}
								onRefresh={this._isLoadRefresh.bind(this)}
								onEndReachedThreshold={1}
								onEndReached={() => { this._loadData() }}
							/>
							: <PageStatusIndex status={status} emptyText="暂无记录" onErrorPress={() => this._onErrorPress()} />
					}
				</View>
				<DelayModel {...this.delayModelData} />
				<InputModel {...this.inputModelData} />
				{timeModel ? <RangTime isVisible={true} markedDates={null} startTime={timeStart} endTime={timeEnd} resultCall={this._resultCall} closeCall={this._cancelCall} /> : null}
				{
					this.state.loading && !this.state.loadIcon ?
						<View style={{ position: 'absolute', height: GLOBAL.SCREEN_HEIGHT, width: GLOBAL.SCREEN_WIDTH, top: 0 }}>
							<PageStatusIndex status='loading' />
						</View>
						: null
				}

				<SlideSelect alertShow={alertShow} options={options}
					select={(val) => {
						this.setState({ choice: val || options[0], alertShow: false }, () => {
							this._isLoadRefresh();
						})
					}}
					unselect={() => {
						this.setState({ alertShow: false })
					}} />
			</View>
		)
	}
}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray
	},
	flexRow: {
		flexDirection: 'row',
		alignItems: 'center',
		paddingLeft: 12 * scale
	},
	dateSelect: {
		flexDirection: 'row',
		marginRight: 4 * scale
	},
	selects: {
		marginBottom: 10 * scale,
		marginLeft: 12 * scale,
	},
	selectItem: {
		padding: 10 * scale
	},
	selectText: {
		color: '#848a96',
		fontSize: 12 * scale
	},
	listScreen: {
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center',
		height: 60 * scale,
	},
	headBox: {
		backgroundColor: style.color.themeColor,
		height: 150 * scale,
		width: '100%',
	},
	outSearch: {
		height: 36 * scale,
		width: '100%',
		flexDirection: 'row',
		justifyContent: 'center',
	},
	nerSearch: {
		height: 36 * scale,
	},
	searchStyle: {
		width: 255 * scale,
		height: 36 * scale,
		backgroundColor: 'rgb(110,178,253)',
		borderRadius: 6 * scale,
		marginLeft: 0
	},
	searchLeftIconStyle: {
		marginLeft: 50 * scale,
		tintColor: '#fff',
	},
	headTab: {
		width: '100%',
		marginTop: 10 * scale,
		flexDirection: 'row',
		justifyContent: 'space-around',
		alignItems: 'center',
		marginBottom: 10 * scale,
	},
	tabText: {
		color: '#fff',
		fontSize: 16 * scale,
		lineHeight: 30 * scale,
		textAlign: 'center',
		width: 70 * scale
	},
	showBoxOut: {
		height: 72 * scale,
		width: '100%',
		flexDirection: 'row',
		justifyContent: 'center',
		marginTop: 16 * scale
	},
	showBox: {
		width: 327 * scale,
		height: 72 * scale,
		borderRadius: 6 * scale,
		backgroundColor: style.color.white,
		flexDirection: 'row',
		justifyContent: 'space-around',
		alignItems: 'center'
	},
	listBoxOut: {
		backgroundColor: '#F4F7FE',
		flex: 1,
		paddingLeft: 12 * scale,
		paddingRight: 12 * scale,
	},
	title: {
		marginTop: 14 * scale,
		fontSize: 13 * scale,
		color: style.color.atrous,
		paddingLeft: 12 * scale
	},
	showText: {
		color: style.color.atrous,
		fontSize: 16 * scale,
		fontWeight: 'bold',
	},
	showTitle: {
		color: '#848A96',
		fontSize: 12 * scale,
		fontWeight: 'bold',
	},
	timeTitle: {
		fontSize: 14 * scale,
		color: '#848A96',
		textAlign: 'right'
	},
	timeValue: {
		fontSize: 12 * scale,
		color: style.color.atrous,
		textAlign: 'right'
	},
	timeRight: {
		width: 150 * scale,
		justifyContent: 'flex-end',
		marginRight: 8 * scale
	},
	allBtn: {
		color: '#0E7FFD',
		fontWeight: 'bold',
		marginRight: 10 * scale,
		fontSize: 14 * scale
	},
	itemHead: {
		height: 35 * scale,
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderBottomColor: style.color.gray,
	},
	itemTitle: {
		fontSize: 13 * scale,
		paddingLeft: 12 * scale,
		paddingRight: 12 * scale,
		color: style.color.atrous,
		lineHeight: 35 * scale
	},
	itemList: {
		marginLeft: 10 * scale,
		marginRight: 10 * scale,
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderBottomColor: style.color.gray,
		paddingTop: 2 * scale,
		paddingBottom: 2 * scale,
	},
	itemHeight: {
		flexDirection: 'row',
		justifyContent: 'space-between',
		paddingTop: 6 * scale,
		paddingBottom: 6 * scale
	},
	money: {
		fontSize: 14 * scale,
		color: style.color.atrous,
		fontWeight: 'bold'
	},
	itemText: {
		color: style.color.atrous,
		fontSize: 13 * scale,
	},
	sellText: {
		color: '#F5A623',
		fontSize: 14 * scale,
		fontWeight: 'bold',
		paddingLeft: 10 * scale
	},
	buyText: {
		color: '#82CD4B',
		fontSize: 14 * scale,
		fontWeight: 'bold',
		paddingLeft: 10 * scale
	},
	total: {
		flexDirection: 'row',
		justifyContent: 'flex-end',
		alignItems: 'center',
		paddingRight: 10 * scale,
		height: 35 * scale
	},
	totalValue: {
		fontSize: 16 * scale,
		fontWeight: 'bold',
	},
	totalKey: {
		fontSize: 12 * scale,
		color: style.color.atrous
	},
	modelOut: { top: 230 * scale },
})